package com.neusoft.neu24.nep.gateway.filter;

import cn.hutool.json.JSONObject;
import com.neusoft.neu24.nep.entity.HttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


@Slf4j
public class AuthenticationGlobalFilter  implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        System.out.println("PASS  AuthenticationGlobalFilter - - - - -  -   - >   ");
        log.info("custom global filter");
        if (System.currentTimeMillis() %2 ==0){
            return chain.filter(exchange);
        }
        System.out.println("  STOP !!!!!!  - - - - -  -   -   ");
        log.info("请求参数中不包含custom参数, 请求非法, 拦截");

        byte[] bits =   ("{\n" +
                "\"code\": 403,\n" +
                "\"msg\": \"无权操作\",\n" +
                "\t\"result\":null \n" +
                "}").getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.OK);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}